/*
 * @(#)UserController.java
 * UserController类作为SpringMVC的Controller层
 * 主要负责对用户方面的请求的映射处理，调用Service层的方法对请求进行处理并返回结果
 * Copyright 2015 上海领智信息科技有限公司, Inc. All rights reserved.
 * @author reeves
 * @Time 2015/04/20 21:37:00
 * @version 1.0
 */

package com.version1_1.controller;

import com.alibaba.fastjson.JSONObject;
import com.util.format.MapToJson;
import com.util.property.Properties;
import com.version1_1.service.UserService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;

/**
 * @author reeves
 * @ClassName: UserController
 * @Description: 用户相关接口控制器
 * @date 2015年4月25日 下午4:47:52
 */
@Controller
public class UserController {

    @Autowired
    private UserService userService;

    /*创建Log4j对象*/
    private static final Logger LOGGER = Logger.getLogger(UserController.class);

    /**
     * 调用接口：http://www.kuibutech.com/kuibuversion1/user/register/{telnumber}/{password}
     *
     * @Description: 用户注册
     */
    @RequestMapping(value = "/user/register/{telnumber}/{password}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String register(@PathVariable("telnumber") String telnumber, @PathVariable("password") String password)
            throws UnsupportedEncodingException {
        try {
            return userService.userRegister(telnumber, "", password);
        } catch (Exception exception) {
            return "{\"isCorrect\":false,\"type\":3,\"userId\":-1}";
        }
    }

    /**
     * 调用接口：http://www.kuibutech.com/kuibuversion1/user/login
     *
     * @Description: 用户登陆
     */
    @RequestMapping(value = "/user/login", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String login(HttpServletRequest request)
            throws UnsupportedEncodingException {
        request.setCharacterEncoding("UTF-8");
        String loginString = (String) request.getParameter("loginString");
        JSONObject reJsonObject = JSONObject.parseObject(loginString);

        // 参数错误
        if (reJsonObject == null) {
            LOGGER.error("用户登陆错误,loginString为null...");
            return "{\"userId\":-1,\"errorType\":2}";
        }

        // 解析JSON参数
        return userService.userLogin(
                reJsonObject.getIntValue("userId"), reJsonObject.getString("mail"),
                reJsonObject.getString("telnumber"),
                reJsonObject.getString("password"), "");
    }

    /**
     * 调用接口：http://www.kuibutech.com/kuibuversion1/user/changePasswd
     *
     * @Description: 登陆用户更改密码
     */
    @RequestMapping(value = "/user/changePasswd", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String changePasswd(HttpServletRequest request)
            throws UnsupportedEncodingException {
        request.setCharacterEncoding("UTF-8");

        String updatePasswdString = request.getParameter("updatePasswdString");

        // 参数错误
        if (updatePasswdString == null) {
            LOGGER.error("登陆用户更改密码错误,updatePasswdString为null...");
            return "{\"updatePasswdResult\":false}";
        }

        // 返回密码更新结果
        return userService.updatePasswd(updatePasswdString);
    }

    /**
     * 调用接口：http://www.kuibutech.com/kuibuversion1/user/updateInfo
     *
     * @Description: 更改用户个人信息
     */
    @RequestMapping(value = "/user/updateInfo", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String updateInfo(HttpServletRequest request)
            throws UnsupportedEncodingException {
        request.setCharacterEncoding("UTF-8");

        /**
         * updateInfoString
         * 格式：{"userId":,"userName":"","userPhoto":"","userSex":"","school":"","schoolYear":(default -1)}
         */
        String updateInfoString = request.getParameter("updateInfoString");
        //String updateInfoString = jsonObject.get("updateInfoString").toString();

        // 参数错误
        if (updateInfoString == null) {
            LOGGER.error("更新用户个人信息错误,updateInfoString为null");
            return "{\"updateResult\":false}";
        }

        return userService.updateUserInfo(updateInfoString);
    }

    /**
     * 调用接口：http://www.kuibutech.com/kuibuversion1/user/updateFocusList
     *
     * @Description: 更新关注列表
     */
    @RequestMapping(value = "/user/updateFocusList", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String updateFocusList(HttpServletRequest request)
            throws UnsupportedEncodingException {
        request.setCharacterEncoding("UTF-8");
        String updateListString = request.getParameter("updateListString");
        //String updateListString = jsonObject.get("updateListString").toString();

        // 参数错误
        if (updateListString == null) {
            LOGGER.error("登陆用户更新关注列表错误,updateListString为null...");
            return "{\"focusUpdateResult\":false}";
        }

        // 返回用户关注列表更新结果
        return userService.updateFocusList(updateListString);
    }

    //TODO:更新用户关注列表（新接口,未完成-12.13）
    @RequestMapping(value = "/user/updateFocusListNew", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String updateFocusListNew(HttpServletRequest request) throws UnsupportedEncodingException {
        request.setCharacterEncoding("UTF-8");

        /**
         * updateListString
         * 格式：
         * {
         *     "userId":,
         *     "updateFocusList":[
         *          {
         *              "itemNumber":,
         *              "focus":[
         *                  {
         *                      "secondType":,
         *                      "thirdName":""
         *                  }...
         *              ]
         *          }...
         *     ]
         * }
         */
        String updateListString = request.getParameter("updateListString");
        //String updateListString = jsonObject.get("updateListString").toString();

        //参数未收到
        if (updateListString == null) {
            LOGGER.error("更新用户关注列表（新接口）,未接收到客户端参数");
            return "{\"focusUpdateResult\":false}";
        }

        //返回用户关注列表更新结果
        return userService.updateFocusListNew(updateListString);
    }


    /**
     * 调用接口：http://www.kuibutech.com/kuibuversion1/user/message/{userId}
     *
     * @Description: 检查是否有消息
     */
    @RequestMapping(value = "/user/message/{userId}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String hasMessage(@PathVariable("userId") int userId) {
        String hasMessage = userService.getMessage(userId);
        /*把是否有消息的结果发送给客户端*/
        return "{\"hasMessage\":" + hasMessage + "}";
    }


    /**
     * 调用接口：http://www.kuibutech.com/kuibuversion1/user/message/reply/{userId}/{pageNumber}
     *
     * @Description: 获取用户回复列表信息
     */
    @RequestMapping(value = "/user/message/reply/{userId}/{pageNumber}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String getReplyMessage(@PathVariable("userId") int userId,
                                  @PathVariable("pageNumber") int pageNumber)
            throws UnsupportedEncodingException {
        return userService.getReplyString(userId, pageNumber,
                Properties.PageSize_UserReply);
    }

    /**
     * 调用接口：http://www.kuibutech.com/kuibuversion1/user/message/praise/{userId}/{pageNumber}
     *
     * @Description: 获取用户点赞列表信息
     */
    @RequestMapping(value = "/user/message/praise/{userId}/{pageNumber}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String getPraiseMessage(@PathVariable("userId") int userId,
                                   @PathVariable("pageNumber") int pageNumber)
            throws UnsupportedEncodingException {
        return userService.getPraiseString(userId,
                pageNumber, Properties.PageSize_Praise);
    }

    /**
     * 调用接口：http://www.kuibutech.com/kuibuversion1/user/message/system/{userId}
     *
     * @Description: 获取用户系统消息, 正在写，需要设计方面给出设计。。。
     */
    @RequestMapping(value = "/user/message/system/{userId}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String getSystemMessage(@PathVariable("userId") int userId)
            throws UnsupportedEncodingException {
        return userService.getSystemMessage(userId);
    }

    /**
     * 调用接口：http://www.kuibutech.com/kuibuversion1/user/feedback
     *
     * @Description: 用户反馈
     */
    @RequestMapping(value = "/user/feedback", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String feedback(HttpServletRequest request)
            throws UnsupportedEncodingException {
        request.setCharacterEncoding("UTF-8");

        String feedbackString = (String) request.getParameter("feedbackString");
        // 参数错误
        if (feedbackString == null) {
            LOGGER.error("用户反馈错误,客户端参数为null...");
            return "{\"code\":500}";
        }

        // 返回用户反馈结果
        return userService.feedback(feedbackString);
    }

    /**
     * 调用接口：http://www.kuibutech.com/kuibuversion1/user/doCollect
     *
     * @Description: 记录、删除用户单次收藏
     */
    @RequestMapping(value = "/user/doCollect", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String doCollect(HttpServletRequest request)
            throws UnsupportedEncodingException {
        request.setCharacterEncoding("UTF-8");
        String collectString = request.getParameter("collectString");

        if (collectString == null) {
            LOGGER.error("记录、删除用户单次收藏错误,collectString为null...");
            return "{\"collectResult\":false}";
        }
        // 返回记录结果
        return userService.doCollect(collectString);
    }

    /**
     * 调用接口：http://www.kuibutech.com/kuibuversion1/user/getCollectList/{userId}/{pageNumber}
     *
     * @Description: 登录用户得到收藏列表
     */
    @RequestMapping(value = "/user/getCollectList/{userId}/{pageNumber}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String getCollectList(@PathVariable("userId") int userId, @PathVariable("pageNumber") int pageNumber)
            throws UnsupportedEncodingException {
        return userService.getCollectList(userId, pageNumber);
    }

    /**
     * 调用接口：http://www.kuibutech.com/kuibuversion1/user/getSecondTypeCollectList/{userId}/{secondType}/{pageNumber}
     *
     * @Description: 根据二级分类ID获取用户收藏中特定的二级分类的文章
     */
    @RequestMapping(value = "/user/getSecondTypeCollectList/{userId}/{secondType}/{pageNumber}", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String getSecondTypeCollectList(@PathVariable("userId") int userId, @PathVariable("secondType") int secondType, @PathVariable("pageNumber") int pageNumber) throws UnsupportedEncodingException {
        return userService.getSecondTypeCollectList(userId, secondType, pageNumber);
    }


    /**
     * 调用接口：http://www.kuibutech.com/kuibuversion1/user/delCollect
     *
     * @Description: 删除用户收藏
     */
    @RequestMapping(value = "/user/delCollect", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String delCollect(HttpServletRequest request)
            throws UnsupportedEncodingException {
        request.setCharacterEncoding("UTF-8");
        String collectDelString = request.getParameter("collectDelString");
        //String collectDelString = jsonObject.get("collectDelString").toString();

        boolean result = true;

        if (collectDelString == null) {
            LOGGER.error("删除用户收藏错误,collectDelString为null...");
            result = false;
        } else {
            JSONObject jsonObject1 = JSONObject.parseObject(collectDelString);
            try {
                userService.delCollect(
                        jsonObject1.getIntValue("userId"),
                        jsonObject1.getString("deleteList"));
            } catch (Exception exception) {
                result = false;
            }
        }

        return new MapToJson("delResult", result).toJsonString();
    }

    /**
     * 调用接口: http://www.kuibutech.com/kuibuversion1/user/checkRegister/{registerInfo}
     *
     * @Description: 验证用户邮箱或手机号已经被注册
     */
    @RequestMapping(value = "/user/checkRegister/{registerInfo}", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String checkRegister(@PathVariable("registerInfo") String registerInfo) {
        /**
         * 客户端请求参数：
         * URL: registerInfo,无论是手机号或是邮箱号都可
         * 服务器响应参数：
         * checkResult:{"isExisted":1/0/-1} 1表示有，0表示没有，-1表示出错
         */
        int result = -1;

        if (registerInfo == null) {
            // 客户端参数获取错误
            LOGGER.error("验证用户邮箱或手机号已经被注册，客户端参数未接收到...");
        } else {
            boolean checkResult = userService.checkRegister(registerInfo);

            if (checkResult) {
                result = 1;
            } else {
                result = 0;
            }
        }

        return new MapToJson("isExisted", result).toJsonString();
    }

    /**
     * 调用接口：http://www.kuibutech.com/kuibuversion1/user/forgetPass/{telnumber}/{newPassword}
     *
     * @description: 忘记密码
     */
    @RequestMapping(value = "/user/forgetPass/{telnumber}/{newPassword:.+}", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String forgetPass(@PathVariable("telnumber") String telnumber, @PathVariable("newPassword") String newPassword) {
        boolean result = false;

        // 如果手机号不是11位或者新密码不足6位
        if ((telnumber.length() != 11) || (newPassword.length() < 6)) {
            LOGGER.error("更改密码，手机号不是11位或新密码不足6位,telnumber: " + telnumber + ", newPassword: " + newPassword);
        } else {
            result = userService.forgetPass(telnumber, newPassword);
        }

        return new MapToJson("forgetPassResult", result).toJsonString();
    }

}
